<template>
  <div class="main">
    <div class="main_login">
      <h3 class="main_login_title">{{ $t("login.name") }}</h3>
      <functionality-button></functionality-button>
      <div class="main_login_form">
        <el-form
          ref="loginForm"
          :model="formData"
          label-width="0px"
          :rules="loginRules"
        >
          <el-form-item label="" prop="account">
            <el-input
              :placeholder="$t('login.account')"
              v-model="formData.account"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="parssWord">
            <el-input
              :placeholder="$t('login.password')"
              type="password"
              v-model="formData.parssWord"
              show-password
            >
            </el-input>
          </el-form-item>
          <el-form-item v-if="HistoricalPas" label="" prop="verificationCode">
            <Verify
              :figure="20"
              :value="formData.verificationCode"
              ref="VerifyCom"
              mode="pop"
              width="auto"
              height="30px"
              :codeLength="4"
              :showButton="false"
              :type="2"
            >
              <template v-slot:input>
                <el-input
                  style="width: 100%"
                  :placeholder="$t('login.verificationEmptyTips')"
                  v-model="formData.verificationCode"
                  maxLength="4"
                >
                </el-input>
              </template>
            </Verify>
          </el-form-item>
          <el-form-item label="">
            <el-checkbox v-model="storage" :label="true">{{
              $t("login.record")
            }}</el-checkbox>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" @click="submit(loginForm)">{{
              $t("login.signIn")
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { useRouter } from "vue-router";
import { reactive, ref, getCurrentInstance, defineAsyncComponent } from "vue";
// @ts-ignore
import Verify from "vue2-verify"; //没有ts
import Cookies from "js-cookie";
import type { FormInstance } from "element-plus";
import { formDataInterface } from "./login";
import { useI18n } from "vue-i18n";
const $t = useI18n().t;
const functionalityButton = defineAsyncComponent(
  () => import("@/components/functionality-button.vue")
);
// 获取i18n$t
const $api = getCurrentInstance()?.appContext.config.globalProperties.$api;
// 更改语言

const router = useRouter();
// 表单
let formData = reactive<formDataInterface>({
  parssWord: "",
  account: "",
  verificationCode: "",
});
let loginForm = ref();
// 验证码状态
let HistoricalPas = ref(true);
let storage = ref<boolean | undefined>(false);
// 验证码内容
let VerifyCom = ref();
/* 加载时 查看是否存有密码 没过期则取出 */
formData.account = Cookies.get("account");
formData.parssWord = Cookies.get("password");
storage.value = !!Cookies.get("storage");
// 如果存在保存密码 隐藏验证码
if (formData.account && formData.parssWord && storage.value) {
  HistoricalPas.value = false;
}
// 自定义验证码 验证
const verificationCodeRules = (
  rule: unknown,
  value: string,
  callback: any
): void => {
  if (formData.parssWord && formData.parssWord.length > 5 && formData.account) {
    if (value) {
      if (VerifyCom.value.checkCode()) {
        callback();
      } else {
        callback(new Error($t("login.verificationErrorTips")));
        // formData.verificationCode = ''
      }
    } else {
      callback(new Error($t("login.verificationEmptyTips")));
    }
  } else {
    callback();
  }
};
// form表单验证
const loginRules = {
  account: [
    { required: true, message: $t("login.accountTips"), trigger: "blur" },
  ],
  parssWord: [
    { required: true, message: $t("login.passwordTips"), trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: $t("login.passwordLengthTips"),
      trigger: "blur",
    },
  ],
  verificationCode: [{ validator: verificationCodeRules, trigger: "blur" }],
};
// 按钮点击登录验证
const submit = async (loginForm: FormInstance) => {
  if (!loginForm) {
    return;
  }
  await loginForm.validate((res, msg) => {
    if (res) {
      loginAction();
    } else {
      console.error(msg);
    }
  });
};
// 请求登录
const loginAction = () => {
  $api.login(formData).then((res: any) => {
    if (res.code == 200) {
      Cookies.set("account", formData.account || "", { expires: 30 });
      Cookies.set("password", formData.parssWord || "", { expires: 30 });
      Cookies.set("storage", storage.value?.toString() || "", { expires: 30 });
      router.replace({ path: "index" });
    } else {
      /* 验证不通过条件 所有状态初始化*/
      Cookies.remove("account");
      Cookies.remove("password");
      Cookies.remove("storage");
      VerifyCom.value.refresh();
      formData.account = undefined;
      formData.parssWord = undefined;
      formData.verificationCode = undefined;
      HistoricalPas.value = true;
      storage.value = false;
    }
  });
};
// loginAction()//自动登录
</script>
<style>
* {
  margin: 0;
  padding: 0;
}

*::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

*::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #ccc;
}

*::-webkit-scrollbar-track-piece {
  background-color: #ccc;
}

#app {
  height: 100vh;
  width: 100vw;
}
</style>
<style lang="scss" scoped>
@import "~@/assets/style/login/index";
</style>